package com.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.dto.MakePurchaseDto;
import com.community.dto.PurchaseOrderDto;
import com.community.pojo.Product;
import com.community.pojo.PurchaseOrder;
import com.community.pojo.PurchaseOrderDetails;
import com.community.service.IProductService;
import com.community.service.IPurchaseOrderDetailsService;
import com.community.service.IPurchaseOrderService;
import com.community.utils.NumberUtils;
import com.community.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TangHaoSong Fly ChenJie HeYuHang
 * @since 2024-05-15
 */
@CrossOrigin
@Controller
@RequestMapping("/community/purchaseOrder")
public class PurchaseOrderController {
    @Autowired
    private NumberUtils numberUtils;
    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    @Autowired
    private IPurchaseOrderDetailsService purchaseOrderDetailsService;
    @Autowired
    private IProductService productService;

    //添加采购单与采购明细单
    @RequestMapping("/addPurchase")
    @ResponseBody
    public String addPurchase(@RequestBody List<MakePurchaseDto> makePurchaseDto){


//        System.out.println(makePurchaseDto);
        // 创建一个Map来存储根据条件分类的对象数组
        HashMap<Integer,List<MakePurchaseDto>> map = new HashMap<>();
        Set<Integer> keySet = map.keySet();
        for (MakePurchaseDto obj : makePurchaseDto){
            //获取供货商id
            int id = obj.getSupplierId();
            if(!map.containsKey(id)){
                map.put(id,new ArrayList<>());
                map.get(id).add(obj);
            }else {
                map.get(id).add(obj);
            }
        }
        System.out.println(map);
        for (Map.Entry<Integer,List<MakePurchaseDto>> entry :map.entrySet() ){
            Integer supplierId = entry.getKey();
            List<MakePurchaseDto> list = entry.getValue();

            //创建采购新数据
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            //新建采购明细新数据
            PurchaseOrderDetails details = new PurchaseOrderDetails();
            Double sumPrice = new Double(0);
            int sumAmount = 0;
            String register = "";
            Date registerTime = new Date();
            String payMethod = "";

            purchaseOrder.setPurchaseId(null);
            // 生成采购单编号
            String designId = numberUtils.getTypeNumber("100");
            purchaseOrder.setPurchaseOrderNumber(designId);

            for (MakePurchaseDto value :list){
                sumPrice += value.getSubtotal();
                sumAmount += value.getCount();
                register = value.getRegister();
                registerTime = value.getRegisterTime();
                payMethod = value.getPayMethod();

            }
            //采购总金额
            purchaseOrder.setTotalPrice(sumPrice);
            //采购总数量
            purchaseOrder.setTotalAmount(sumAmount);
            //供应商id
            purchaseOrder.setSupplierId(supplierId);
            //登记人
            purchaseOrder.setRegister(register);
            //登记时间
            purchaseOrder.setRegisterTime(registerTime);
            //入库标志,K001-1（等待入库）、K001-2（入库失败）、K001-2（入库成功）
            purchaseOrder.setGatherTag("K001-1");
            //支付方式，P002-1（余额支付）、P002-2（微信支付）、P003（现金支付）
            purchaseOrder.setPayMethod(payMethod);
            //审核标志,S001-1（等待审核）、S001-2（审核未通过）、S001-3（审核通过）
            purchaseOrder.setCheckTag("S001-1");
            //向数据库插入采购数据
            purchaseOrderService.save(purchaseOrder);


            for (MakePurchaseDto value :list){
                int purchaseId = purchaseOrder.getPurchaseId();
                //采购明细id
                details.setId(null);
                //采购订单id
                details.setPurchaseId(purchaseId);
                //商品id
                details.setProductId(value.getProductId());
                //采购数量
                details.setCount(value.getCount());
                //单价
                details.setPrice(value.getPrice());
                //总价
                details.setSubtotal(value.getSubtotal());
                //入库标志，K001-1（等待入库）、K001-2（入库失败）、K001-2（入库成功）
                details.setGatherTag("K001-1");
                //向数据库插入采购明细数据
                purchaseOrderDetailsService.save(details);
            }
        }


        return "ok";
    }

    //查询所有待审核的采购单
    @RequestMapping("/checkList")
    @ResponseBody
    public List<PurchaseOrder> checkList(){
        QueryWrapper<PurchaseOrder> wrapper = new QueryWrapper<>();
        //审核标志,S001-1（等待审核）
        wrapper.eq("check_tag", "S001-1");
        List<PurchaseOrder> list = this.purchaseOrderService.list(wrapper);

        return list;
    }

    //根据id查询待审核的采购单
    @RequestMapping("/purchaseOrderById")
    @ResponseBody
    public Object purchaseOrderById(int purchaseId){
        return this.purchaseOrderService.getById(purchaseId);
    }

    //审核不通过的采购单
    @RequestMapping("/noPass")
    @ResponseBody
    public Object noPass(@RequestBody PurchaseOrder purchaseOrder){
        //审核标志,S001-1（等待审核）、S001-2（审核未通过）、S001-3（审核通过）
        purchaseOrder.setCheckTag("S001-2");
        purchaseOrderService.updateById(purchaseOrder);

        return "审核不通过";
    }
    //审核通过的采购单
    @RequestMapping("/pass")
    @ResponseBody
    public Object pass(@RequestBody PurchaseOrder purchaseOrder){
        //System.out.println(purchaseOrder);
        //审核标志,S001-1（等待审核）、S001-2（审核未通过）、S001-3（审核通过）
        purchaseOrder.setCheckTag("S001-3");
        //配送标志，P001-1（待发货）、P001-2（待收货）、P001-3（已收货）
        purchaseOrder.setConveyTag("P001-1");
        purchaseOrderService.updateById(purchaseOrder);

        return "审核通过";
    }

    //分页查询所有采购单
    @RequestMapping("/queryAll")
    @ResponseBody
    public PageUtils<PurchaseOrder> queryAll(int pageNo, int pageSize){
        return this.purchaseOrderService.searchAll(pageNo,pageSize);
    }

    //根据供应商id查询待发货审核通过的采购单表
    @RequestMapping("/purchaseById")
    @ResponseBody
    public Object purchaseById(int id){
        QueryWrapper<PurchaseOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("supplier_id",id);
        //审核标志,S001-1（等待审核）、S001-2（审核未通过）、S001-3（审核通过）
        wrapper.eq("check_tag","S001-3");
        //配送标志，P001-1（待发货）、P001-2（待收货）、P001-3（已收货）
        wrapper.eq("convey_tag","P001-1");
        List<PurchaseOrder> list = this.purchaseOrderService.list(wrapper);

        return list;
    }
    //根据id发出对应的货物
    @RequestMapping("/updateById")
    @ResponseBody
    public Object updateById(int id){
        PurchaseOrder purchaseOrder = this.purchaseOrderService.getById(id);
        if (purchaseOrder!=null){
            //配送标志，P001-1（待发货）、P001-2（待收货）、P001-3（已收货）
            purchaseOrder.setConveyTag("P001-2");

            purchaseOrderService.updateById(purchaseOrder);
        }
        return "发货成功";
    }
    //分页查询所有已审核的采购单
    @RequestMapping("checkedList")
    @ResponseBody
    public PageUtils<PurchaseOrder> checkedList(int pageNo, int pageSize){
        return this.purchaseOrderService.queryAllChecked(pageNo,pageSize);
    }
}


